﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using Entity;
using BAL;
using Common;

namespace Web
{
    public partial class PostQuestion : System.Web.UI.Page
    {
        private IList<DifficInfo> Difficinfos = new List<DifficInfo>();
        private IList<QuesTypeInfo> QuesTypeInfos = new List<QuesTypeInfo>();
        private IList<LevelInfo> LevelInfos = new List<LevelInfo>();
        private IList<CognitiveLevelInfo> CognitiveLevelInfos = new List<CognitiveLevelInfo>();
        private IList<BookInfo> BookInfos = new List<BookInfo>();
        private int delid = 0, editid = 0, _count = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!UserValidate.CheckLogin(this.Request, "QuesAdd"))
            {
                Response.Write("<script type=\"text/javascript\">top.location.href='login.aspx';</script>");
                Response.Redirect("login.aspx");
                Response.End();
            }

            if (Request.QueryString["delid"] != null && Request.QueryString["delid"] != string.Empty)
            {
                if (PageValidate.IsNumber(Request.QueryString["delid"]))
                {
                    delid = int.Parse(Request.QueryString["delid"]);
                }
            }
            if (Request.QueryString["editid"] != null && Request.QueryString["editid"] != string.Empty)
            {
                if (PageValidate.IsNumber(Request.QueryString["editid"]))
                {
                    editid = int.Parse(Request.QueryString["editid"]);
                }
            }
            if (!IsPostBack)
            {
                if (editid > 0)//编辑时传来的ID
                {
                    QuestionInfo questionInfo = new QuestionInfo();
                    questionInfo = Question.GetQuestionInfoById(editid);
                    QuesTypeId.Text = QuesType.GetQuesTypeInfoById(questionInfo.QuesTypeId).Keyword;
                    DifficId.Text = Diffic.GetDifficInfoById(questionInfo.DifficId).Keyword;
                    LevelId.Text = questionInfo.LevelId.ToString();
                    Score.Text = questionInfo.Score.ToString();
                    AbilityId.Text = questionInfo.AbilityId.ToString();
                    KeyWord.Text = questionInfo.KeyWord;
                    Printer.Text = questionInfo.Printer;
                    SubjectId.Text = Subject.GetSubjectInfoById(questionInfo.SubjectId).Keyword;
                    SetSubjectId(questionInfo.SubjectId);
                    ComputeTime.Text = questionInfo.ComputeTime.ToString();
                    CheckBoxListHelper.SetSelectedValue(SubKnowsList, questionInfo.SubKnow);//选中判断（次要知识点）
                    CheckBoxListHelper.SetSelectedValue(ROCList, questionInfo.ROC);//选中判断（版本信息）

                    CognitiveLevelId.Text = CognitiveLevel.GetSingleInfo(questionInfo.CognitiveLevelId).Keyword;
                    if (questionInfo.PrinterId > 0)
                    {
                        HiddenEmail.Value = Users.GetUserInfoById(questionInfo.PrinterId).Email;
                    }
                    PrintDate.Text = questionInfo.PrintDate.Date.ToString();
                    Title.Value = questionInfo.Title.Replace("\"upfile/", "\"../../upfile/");
                    AnswerNew.Value = questionInfo.Answer;
                    _count = questionInfo.Counts;
                    KnowId.Text = Knowledge.GetKnowledgeInfoById(questionInfo.KnowId).Keyword;
                }
                if (delid > 0)//删除时传来的ID
                {
                    if (!UserValidate.CheckLogin(this.Request, "QuesDel"))
                    {
                        Response.Write("<script type=\"text/javascript\">top.location.href='login.aspx';</script>");
                        Response.Redirect("login.aspx");
                        Response.End();
                    }
                    QuestionInfo qinfo = Question.GetQuestionInfoById(delid);
                    if (qinfo.StatusId != 4 && qinfo.StatusId != 8 && qinfo.StatusId != 6)
                    {
                        if (Request.QueryString["PageState"] != null)
                        {
                            Response.Redirect(Common.DESEncrypt.Decrypt(Request.QueryString["PageState"]));
                        }
                        else
                        {
                            Response.Redirect("adminquestion.aspx");
                        }
                    }
                    if (UserValidate.CheckLogin(this.Request, "FirstTrial") ||UserValidate.CheckLogin(this.Request, "FinalInstance"))
                    {
                        if (Request.QueryString["PageState"] != null)
                        {
                            Response.Redirect(Common.DESEncrypt.Decrypt(Request.QueryString["PageState"]));
                        }
                        else
                        {
                            Response.Redirect("adminquestion.aspx");
                        }
                    }
                    Paper_Ques.Del(0,delid);//删除关联表中的数据
                    Question.DelQuestion(delid);//删除题目数据
                    if (Request.QueryString["PageState"] != null)
                    {
                        Response.Redirect(Common.DESEncrypt.Decrypt(Request.QueryString["PageState"]));
                    }
                    else
                    {
                        Response.Redirect("adminquestion.aspx");
                    }
                }

                LoadDiffic();//加载试题难度数据方法
                LoadQuesType();
                LoadLevel();
                LoadCognitiveLevel();
                LoadSubject();

                if (Request.QueryString["post"] != null)
                {
                    Utility.ShowBoxyAlert("添加成功，请继续", this);
                }
            }

        }

        protected void LoadSubject()
        {
            SubjectIdList.Items.Clear();
            IList<SubjectInfo> Subject_Infos = new List<SubjectInfo>();
            SubjectIdList.Items.Add(new ListItem("请选择课程", "0"));
            Subject_Infos = Subject.GetSubjectInfos();
            foreach (SubjectInfo info in Subject_Infos)
            {
                SubjectIdList.Items.Add(new ListItem(info.Name, info.Keyword));
            }
        }


        protected void LoadDiffic()
        {
            Difficinfos = Diffic.GetDifficInfos(0, 0);
            DifficIdList.Items.Clear();
            DifficIdList.Items.Add(new ListItem("请选择难度级别", ""));
            foreach (DifficInfo info in Difficinfos)
            {
                DifficIdList.Items.Add(new ListItem(info.Name.ToString() + "    " + info.Keyword.ToString(), info.Keyword.ToString()));
            }
        }

        protected void LoadCognitiveLevel()
        {
            CognitiveLevelInfos = CognitiveLevel.GetList(0);
            CognitiveLevelIdList.Items.Clear();
            CognitiveLevelIdList.Items.Add(new ListItem("请选择认知层次", ""));
            foreach (CognitiveLevelInfo info in CognitiveLevelInfos)
            {
                CognitiveLevelIdList.Items.Add(new ListItem(info.Name+"    "+info.Keyword, info.Keyword));
                IList<CognitiveLevelInfo> subInfos = CognitiveLevel.GetList(info.Id);
                foreach (CognitiveLevelInfo subinfo in subInfos)
                {
                    CognitiveLevelIdList.Items.Add(new ListItem("|——" + subinfo.Name + "    " + subinfo.Keyword, subinfo.Keyword));
                }
            }
        }

        protected void LoadQuesType()
        {
            QuesTypeInfos = QuesType.GetQuesTypeInfos(0, 0);
            QuesTypeIdList.Items.Clear();
            QuesTypeIdList.Items.Add(new ListItem("请选择试题类型", ""));
            foreach (QuesTypeInfo info in QuesTypeInfos)
            {
                QuesTypeIdList.Items.Add(new ListItem(info.Name+"    "+info.Keyword,info.Keyword));
            }
        }

        protected void LoadLevel()
        {
            LevelInfos = Level.GetLevelInfos(0, 0);
            LevelIdList.Items.Clear();
            LevelIdList.Items.Add(new ListItem("请选择优先级", ""));

            foreach (LevelInfo info in LevelInfos)
            {
                LevelIdList.Items.Add(new ListItem(info.Name.ToString(), info.Id.ToString()));
            }
        }
        //加载使用范围
        protected void LoadBook(int inputSubjectId)
        {
            BookInfos = Book.GetBookInfosBySubject(inputSubjectId, 0, 0);
            //ROC.Items.Clear();
            ROCList.Items.Clear();
            foreach (BookInfo info in BookInfos)
            {
                //ROC.Items.Add(new ListItem(info.Name.ToString(), info.Id.ToString()));
                ROCList.Items.Add(new ListItem(info.Name.ToString(), info.Id.ToString()));
            }
        }
        //加载知识树
        protected void LoadKnowledge(int ParentID,int inputSubjectId, string line)
        {
            if (ParentID == 0)
            {
                KnowIdList.Items.Clear();
                SubKnowsList.Items.Clear();
                KnowIdList.Items.Add(new ListItem("请选择知识点", "0"));
                IList<KnowledgeInfo> knowledgeInfos = Knowledge.GetRootKnowledgeInfo(0, inputSubjectId);
                foreach (KnowledgeInfo info in knowledgeInfos)
                {
                    ListItem item = new ListItem(info.Keyword+"  "+info.Name, info.Keyword);//+ "    " + info.Keyword
                    KnowIdList.Items.Add(item);
                    item = new ListItem(info.Keyword, info.Keyword);
                    SubKnowsList.Items.Add(item);//次要知识点添加
                    LoadKnowledge(info.Id, inputSubjectId, "|——");
                }
            }
            else
            {
                IList<KnowledgeInfo> knowledgeInfos = Knowledge.GetKnowledgeInfos(ParentID);//通过parentId获取子集合
                foreach (KnowledgeInfo info in knowledgeInfos)
                {
                    ListItem item = new ListItem(line+ info.Keyword+"  "+ info.Name , info.Keyword);//+ "    " + info.Keyword
                    KnowIdList.Items.Add(item);
                    item = new ListItem(line + info.Keyword, info.Keyword);
                    SubKnowsList.Items.Add(item);
                    LoadKnowledge(info.Id, inputSubjectId, "|——" + line);
                }
            }
        }
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            string _ROC=null,_Printer = null, _Title = null, _QuesTypeKeyword = null, _DifficKeyword = null, _KnowKeyword = null, _SubjectKeyword = null, _BookKeyword = null;
            string _KeyWord = KeyWord.Text.Trim();
            string _Answer = AnswerNew.Value.Trim();
            string _Email = HiddenEmail.Value.Trim();
            string _SubKnow = CheckBoxListHelper.SelectedValue(SubKnowsList);
            decimal _Score = 0;
            int _LevelId = 0, _QuesTypeId = 0, _AbilityId = 0, _DifficId = 0, _KnowId = 0, _CognitiveLevelId = 0, _ComputeTime = 0, _SubjectId = 0;
            DateTime _PrintDate = DateTime.Today;
            if (ROCList.SelectedValue.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须选择适用范围", this);
                return;
            }
            else
            {
                _ROC = CheckBoxListHelper.SelectedValue(ROCList);
            }
            if (QuesTypeId.Text.Trim()=="")
            {
                Utility.ShowBoxyAlert("必须设定题目类型", this);
                return;
            }
            else if (!QuesType.CheckQuesTypeExistByKeyword(QuesTypeId.Text.Trim(),0))
            {
                Utility.ShowBoxyAlert("题目类型编码错误，请核实", this);
                return;
            }
            else
            {
                _QuesTypeKeyword = QuesTypeId.Text.Trim();
                _QuesTypeId = QuesType.GetQuesTypeIdByKeyword(_QuesTypeKeyword);
            }

            if (DifficId.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须设定题目难度", this);
                return;
            }
            else if (!Diffic.CheckDifficExistByKeyword(DifficId.Text.Trim(), 0))
            {
                Utility.ShowBoxyAlert("题目难度编码错误，请核实", this);
                return;
            }
            else
            {
                _DifficId = Diffic.GetDifficIDByKeyword(DifficId.Text.Trim());
            }

            if (CognitiveLevelId.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须设定认知层次", this);
                return;
            }
            else if (!CognitiveLevel.CheckCognitiveLevelExistByKeyword(CognitiveLevelId.Text.Trim(), 0))
            {
                Utility.ShowBoxyAlert("题目认知层次编码错误，请核实", this);
                return;
            }
            else
            {
                _CognitiveLevelId = CognitiveLevel.GetCognitiveLevelIDByKeyword(CognitiveLevelId.Text.Trim());
            }

            if (LevelId.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须设定优先级别", this);
                return;
            }
            else if (!PageValidate.IsNumberSign(LevelId.Text.Trim()))
            {
                Utility.ShowBoxyAlert("优先级别只能是一个正数", this);
                return;
            }
            else
            {
                _LevelId = int.Parse(LevelId.Text.Trim());
            }

            if (AbilityId.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须设定学科能力", this);
                return;
            }
            else if (!PageValidate.IsNumberSign(AbilityId.Text.Trim()))
            {
                Utility.ShowBoxyAlert("学科能力只能是一个正数", this);
                return;
            }
            else
            {
                _AbilityId = int.Parse(AbilityId.Text.Trim());
            }

            if (SubjectId.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("请选择科目", this);
                return;
            }
            else if (!Subject.CheckSubjectExistByKeyword(SubjectId.Text.Trim(), 0))
            {
                Utility.ShowBoxyAlert("科目编码错误，请核实", this);
                return;
            }
            else
            {
                _SubjectKeyword = SubjectId.Text.Trim();
                _SubjectId = Subject.GetSubjectIdByKeyword(SubjectId.Text.Trim());
            }

            if (KnowId.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须选择知识点", this);
                return;
            }
            else if (!Knowledge.CheckKnowledgeExistByKeyword(KnowId.Text.Trim(), 0,_SubjectId))
            {
                Utility.ShowBoxyAlert("知识点编码错误，请核实", this);
                return;
            }
            else
            {
                _KnowKeyword = KnowId.Text.Trim();
                _KnowId = Knowledge.GetKnowledgeIDByKeyword(KnowId.Text.Trim(),_SubjectId);
            }

            if (Score.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须设定题目分数", this);
                return;
            }
            else //对字符的处理
            {
                try
                {
                    Convert.ToSingle(Score.Text.Trim());
                }
                catch (Exception ex)
                {
                    Utility.ShowBoxyAlert("分值必须为数字类型", this);
                    return;
                }
            }
            //限定题目分数范围(0.5~60)
             if (Convert.ToSingle(Score.Text.Trim()) < 0.5 || Convert.ToSingle(Score.Text.Trim())> 600)
            {
                Utility.ShowBoxyAlert("设定题目分数必须在（0.5~600）范围内",this);
                return;
            }
            else if (Score.Text.Trim().LastIndexOf('.') != -1)
            {

                if (Convert.ToInt32(Score.Text.Trim().Substring(Score.Text.Trim().LastIndexOf('.') + 1, 1)) != 5 && Convert.ToInt32(Score.Text.Trim().Substring(Score.Text.Trim().LastIndexOf('.') + 1, 1)) != 0)
                {
                Utility.ShowBoxyAlert("题目分值的小数点后仅能为5", this);
                return;
                }
            }
            _Score = decimal.Parse(Score.Text.Trim());
           

            if (ComputeTime.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须设定估计时间", this);
                return;
            }
            else //对输入字符的处理
            {
                try
                {
                    Convert.ToInt32(ComputeTime.Text.Trim());
                }
                catch (Exception ex)
                {
                    Utility.ShowBoxyAlert("时间必须为数字类型",this);
                    return;
                }
            }
            //限定答题时间
            if (Convert.ToInt32(ComputeTime.Text.Trim()) < 1 || Convert.ToInt32(ComputeTime.Text.Trim()) > 10000)
            {
                Utility.ShowBoxyAlert("估计答题时间必须在（1~10000）范围内",this);
            }
            else
            {
                _ComputeTime = int.Parse(ComputeTime.Text.Trim());
            }

            if (Printer.Text.Trim() == "")
            {
                Utility.ShowBoxyAlert("必须填写出题人", this);
                return;
            }
            else
            {
                _Printer = Printer.Text.Trim();
            }

            if (PrintDate.Text.Trim() != "")
            {
                if (PageValidate.IsDateTime(PrintDate.Text.Trim()))
                {
                    _PrintDate = Convert.ToDateTime(PrintDate.Text.Trim());
                }
                else
                {
                    Utility.ShowBoxyAlert("出题时间必须是一个日期", this);
                    return;
                }
            }
            else
            {
                _PrintDate = DateTime.Today;
            }

            if (Title.Value.Trim().Length < 10)
            {
                Utility.ShowBoxyAlert("题目内容过短", this);
                return;
            }
            else
            {
                _Title = Title.Value.Trim().Replace("\"../../upfile/", "\"upfile/");
            }

            KnowledgeInfo k1 = Knowledge.GetKnowledgeInfoById(_KnowId);
            _SubjectKeyword = Subject.GetSubjectInfoById(Convert.ToInt32(k1.Subject)).Keyword;
            //_BookKeyword = Book.GetBookInfoById(Convert.ToInt32(k1.Book)).Keyword;
            QuestionInfo q1 = new QuestionInfo();
            if (editid > 0)
            {
                q1 = Question.GetQuestionInfoById(editid);
            }
            q1.Answer = _Answer;
            q1.CognitiveLevelId = _CognitiveLevelId;
            q1.BookId = Convert.ToInt32(k1.Book);
            q1.DifficId = _DifficId;
            q1.KeyWord = _KeyWord;
            q1.KnowId = _KnowId;
            q1.LevelId = _LevelId;
            q1.AbilityId = _AbilityId;
            q1.PrintDate = _PrintDate;
            q1.SubjectId = _SubjectId;
            q1.CognitiveLevelId = _CognitiveLevelId;
            q1.ComputeTime = _ComputeTime;
            q1.SubKnow = _SubKnow;
            q1.ROC = _ROC;
            
            if (_Email != "")
            {
                if (Users.CheckUserExistByEmail(_Email))
                {
                    UserInfo qinfo = Users.GetUserInfoByEmail(_Email);
                    q1.PrinterId = qinfo.Id;
                    q1.Printer = qinfo.Name;
                }
                else
                {
                    q1.PrinterId = 0;
                    q1.Printer = _Printer;
                }
            }
            else
            {
                q1.Printer = _Printer;
                q1.PrinterId = 0;
            }
            q1.QuesTypeId = _QuesTypeId;
            q1.Score = _Score;
            q1.State = 4;
            q1.StatusId = 4;
            q1.SubjectId = Convert.ToInt32(k1.Subject);
            q1.Title = _Title;
            if (editid == 0)
            {
                UserLinkExtendInfo uinfo = UserValidate.GetInfo(this.Request);
                int count = Question.GetQuestionMax(new QuestionInfo { QuesTypeId = _QuesTypeId, KnowId = _KnowId }) + 1;
                q1.Serial = _SubjectKeyword  + "-" + _KnowKeyword + "-" + _QuesTypeKeyword + "-" + count.ToString().PadLeft(4, Char.Parse("0"));
                q1.Counts = count;
                if (uinfo != null)
                {
                    q1.UserId = uinfo.Id;
                }
                else
                {
                    q1.UserId = 11;
                }
                q1.Remark = "";
                q1.CreateDate = DateTime.Now;
                Question.AddQuestion(q1);
                Utility.ShowBoxyConfirm("添加成功，是否清除已有选项？", "PostQuestion.aspx",this);
                Title.Value = "";
                AnswerNew.Value = "";
                KeyWord.Text = "";
                Printer.Text = "";
                PrintDate.Text = "";
                return;
                //Response.Redirect("PostQuestion.aspx?post=ok");
            }
            else
            {
                q1.Id = editid;
                q1.Serial = _SubjectKeyword + "-"  + _KnowKeyword + "-" + _QuesTypeKeyword + "-" + _count.ToString().PadLeft(4, Char.Parse("0"));
                Question.EditQuestion(q1);
                //Response.Redirect("adminquestion.aspx");
                if (Request.QueryString["PageState"]!=null)
                {
                    Response.Redirect(Common.DESEncrypt.Decrypt(Request.QueryString["PageState"]));
                }
                else 
                {
                    Response.Redirect("adminquestion.aspx");
                }
                
            }
        }

        protected void SetSubjectId(int inputSubjectId)
        {

            if (inputSubjectId != 0)
            {
                LoadKnowledge(0, inputSubjectId, "——");
                LoadBook(inputSubjectId);
                SetAbility(inputSubjectId);
                KnowId.Text = "";
                AbilityList.Visible = true;
                ROCLabel.Visible = true;
                KnowIdList.Visible = true;
                SubKnowLabel.Visible = true;
            }
        }

        protected void SubjectIdList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SubjectIdList.SelectedIndex > -1)
            {
                int tSubjectId = Subject.GetSubjectIdByKeyword(SubjectIdList.SelectedValue.ToString());//通过关键字获取科目ID
                SetSubjectId(tSubjectId);//通过科目ID设置有关数据的读取
            }
        }

        protected void SetAbility(int inputSubjectId)
        {
            IList<SubjectAbilityInfo> subjectAbilityInfos = BAL.SubjectAbility.GetAbilityInfosBySubjectId(inputSubjectId);
            AbilityList.Items.Clear();
            AbilityList.Items.Add(new ListItem("请选择学科能力", "0"));
            foreach (SubjectAbilityInfo subjectAbilityInfo in subjectAbilityInfos)
            {
                AbilityList.Items.Add(new ListItem(subjectAbilityInfo.Name + "   " + subjectAbilityInfo.Keyword, subjectAbilityInfo.Keyword));
            }
        }
        //文本框改变事件
        protected void SubjectId_TextChanged(object sender, EventArgs e)
        {
            //this.SubjectId.Attributes.Add("onchange", "javaScript:alert(' 测试');");
        }
    }
}
